import {Log} from "./Log";
export class TimeEvent {
    lastExecTime = new Date();
    func: (()=>(void|Promise<void>))|null = null;
    id: number = TimeEvent.incEventId++;

    private static incEventId = 0;
    private static eventMap = new Map<number,TimeEvent>();

    constructor() {
        // this.lastExecTime.setDate(this.lastExecTime.getDate() - 1);
    }

    /**
     * 开始执行定时事件
     */
    start() {
        TimeEvent.set(this);
    }

    /**
     * 暂停执行
     */
    stop() {
        TimeEvent.remove(this);
    }

    private static init() {
        setTimeout(TimeEvent.eventLoop, 20 * 1000);
    }

    /**
     * 循环事件
     * @param intervalTime 事件执行的时间间隔(毫秒)
     * @param func
     */
    static intervalEvent(intervalTime: number, func: (e: TimeEvent)=>(void|Promise<void>)) {
        let ev = new TimeEvent();
        ev.func = ()=> {
            if (Date.now() > ev.lastExecTime.getTime() + intervalTime) {
                ev.lastExecTime = new Date();
                func(ev);
            }
        }

        return ev;
    }


    /**
     * 每日事件
     * @param hours 每日事件执行的时间(时,分)
     * @param minutes
     * @param func
     */
    static dailyEvent(hours: number, minutes: number, func: (e: TimeEvent)=>(void|Promise<void>)) {
        let ev = new TimeEvent();
        ev.func = ()=> {
            var now = new Date();
            // var h = ev.lastExecTime.getDate();
            if (ev.lastExecTime.getDate() != now.getDate() && now.getHours() >= hours && now.getMinutes() >= minutes) {
                ev.lastExecTime = new Date();
                func(ev);
            }
        }

        return ev;
    }

    private static isStart = false;


    /**
     * 设置定时时间
     * @param event
     */
    static set(event: TimeEvent) {
        if (!TimeEvent.isStart) {
            TimeEvent.init();
            TimeEvent.isStart = true;
        }

        TimeEvent.eventMap.set(event.id, event);
    }

    static remove(event: TimeEvent) {
        TimeEvent.eventMap.delete(event.id);
    }

    private static eventLoop() {
        for (var m of TimeEvent.eventMap) {
            var k = m[0];
            var v = m[1];

            try {
                if (v.func)
                    v.func();
            } catch (e) {
                Log.err(e);
            }
        }
        TimeEvent.init();
    }
}